package edu.uic.ids517.servlet;

import java.io.*;

import javax.servlet.*;
import javax.servlet.http.*;

import edu.uic.ids517.model.DatabaseAccessBean;
import edu.uic.ids517.model.DbLoginBean;

public class DbLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		System.out.println("DbLoginServlet");
		String successUrl = "/UserLogin.jsp";
		String failureUrl = "/Error.jsp";
		HttpSession session = request.getSession();

		/*** DbLoginBean ****/
		DbLoginBean userInfo = (DbLoginBean) session
				.getAttribute("dbmsUserBean");
		userInfo.setSessionId(session.getId());
		userInfo.setUserName(request.getParameter("userName"));
		userInfo.setPassword(request.getParameter("password"));
		userInfo.setDbmsHost(request.getParameter("host"));
		userInfo.setDbms(request.getParameter("dbms"));
		userInfo.setDatabaseSchema(request.getParameter("databaseSchema"));

		DatabaseAccessBean dbase = (DatabaseAccessBean) session
				.getAttribute("dbaseBean");
		dbase.setDbmsUserBean(userInfo);

		boolean status = false;
		status = dbase.openConnection();

		if(status){
			System.out.println("Databse Connection Sucessful!!");
			dbase.closeConnection();
			session.setAttribute("sessionValidation", "validSession");

			RequestDispatcher dispatcher = request.getRequestDispatcher(successUrl);
			dispatcher.forward(request, response);
		}
		else{
			RequestDispatcher dispatcher = request.getRequestDispatcher(failureUrl);
			request.setAttribute("errorMessage", "DbLogin Failure: Invalid username/password/host/schema combination");
			dispatcher.forward(request, response);
		}
	}
}
